using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.IO;
using RideMe.Core.Properties;
using System.Reflection;

namespace RideMe.Core
{
    public static class SnippetService
    {
        private static XmlDocument _snippetsDoc;

        /// <summary>
        /// Looks for a snippet matching the key.
        /// </summary>
        /// <param name="key">Key to match.</param>
        /// <returns>The snippet.</returns>
        public static string FindSnippet(string key)
        {
            LoadSnippetDocument();

            XmlNodeList codeSnippetNodes = _snippetsDoc.GetElementsByTagName(Resources.SnippetTagName);

            foreach (XmlNode node in codeSnippetNodes)
            {
                foreach (XmlNode child in node.ChildNodes)
                {
                    if (child.Name == Resources.ShortcutAttribute)
                    {
                        if (child.InnerText == key)
                        {
                            return child.NextSibling.InnerText;                            
                        }
                    }
                }
            }

            return string.Empty;
        }

        public static List<Snippet> GetSnippets()
        {
            return SerializationService.DeserializeSnippets(Path.GetDirectoryName(typeof(SnippetService).Assembly.Location) + Resources.SnippetFilePath);
        }

        public static void SaveSnippets(List<Snippet> snippets)
        {
            SerializationService.SerializeSnippets(Path.GetDirectoryName(typeof(SnippetService).Assembly.Location) + Resources.SnippetFilePath, snippets);
        }

        /// <summary>
        /// Load the snippet XML doc into memory.
        /// </summary>
        private static void LoadSnippetDocument()
        {
            _snippetsDoc = new XmlDocument();

            _snippetsDoc.Load(Path.GetDirectoryName(typeof(SnippetService).Assembly.Location) + Resources.SnippetFilePath);

        }
    }
}
